package jdbc3;

import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 测试事务回滚
 */
public class userStransction {
    @Test
    public void useTransaction() throws SQLException {
        // 1. 得到连接
        Connection connection = null;
        //2. 组织一个 sql
        String sql = "update goods set goods_num = goods_num-50 where id = 1";
        String sql2 = "update goods set goods_num = goods_num+50  where id = 2";
        PreparedStatement preparedStatement = null;
        //3. 创建 PreparedStatement 对象
        try {
            String url = "jdbc:mysql://localhost:3306/yizhuo?useSSL=false&serverTimezone=UTC";
            String username = "root";
            String password = "123456";
            connection = DriverManager.getConnection(url, username, password);
            //将 connection 设置为不自动提交
            connection.setAutoCommit(false); //开启了事务
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate(); // 执行第1 条sql

            int i = 1 / 0; //抛出异常

            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate(); // 执行第3 条sql
            // 这里提交事务
            connection.commit();
        } catch (SQLException e) {
            //这里我们可以进行回滚，即撤销执行的 SQL
            // 默认回滚到事务开始的状态.
            System.out.println("执行发生了异常，撤销执行的sql");
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            //关闭资源
            preparedStatement.close();
            connection.close();
        }
    }
}

